﻿using System;
using System.Diagnostics;
using Avalonia.Controls;
using Avalonia.Interactivity;
using iOSClub.App.Desktop.ViewModels.Pages;
using iOSClub.App.Share;
using iOSClub.App.Share.WeatherModels;

namespace iOSClub.App.Desktop.Pages;

public partial class HomePage : UserControl
{
    public HomePage()
    {
        InitializeComponent();
    }

    private void LinkClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Button button) return;
        if (button.DataContext is not Entry entry) return;
        var uri = new Uri(entry.Link[0].Href);
        Process.Start(new ProcessStartInfo(uri.ToString())
            { UseShellExecute = true, Verb = "open" });
    }

    protected override async void OnInitialized()
    {
        base.OnInitialized();
        if (DataContext is not HomePageModel model) return;
        var now = await Weather.GetNow(Weather.DefaultCity.id);
        if (now != null) model.Now = now;
        var warning = await Weather.GetWarning(Weather.DefaultCity.id);
        if (warning != null) model.Warning = warning;
        model.IsLoad = true;

        var list = await WebArticle.GetArticleAsync();
        foreach (var entry in list)
        {
            model.Articles.Add(entry);
        }

        model.IsArticlesLoad = true;
    }
}